package com.ruoyi.web.controller.common;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.config.properties.FaceProperties;
import com.ruoyi.common.config.properties.OcrProperties;
import com.ruoyi.common.core.domain.*;
import com.ruoyi.common.utils.ocr.IDCardUtil;
import com.ruoyi.common.utils.ocr.OcrUtil;
import com.ruoyi.sms.config.properties.JXSmsProperties;
import com.ruoyi.sms.core.JXSmsTemplate;
import com.ruoyi.sms.entity.JXSmsResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@RequestMapping("/app")
@SaIgnore
@Slf4j
public class AppController {

    @Resource
    private OcrProperties ocrProperties;

    @Resource
    private JXSmsProperties jxSmsProperties;

    @Resource
    private FaceProperties faceProperties;

    @PostMapping("/ocr/sfz")
    public OcrResult sfz(@RequestBody Map<String, Object> params) {
        return new OcrUtil(ocrProperties).sfzOcr(null, params);
    }

    @PostMapping("/ocr/idcard")
    public R idcard(@RequestPart("file") MultipartFile file) {

        if (!faceProperties.getEnabled()) {
            return R.fail("请先开启OCR功能");
        }
        log.info("开始识别身份证1{}", file.getOriginalFilename());

        if (file.isEmpty() || file.getOriginalFilename() == null){
            return R.fail("请上传图片");
        }
        String originalFilename = file.getOriginalFilename();

        //是否是png格式图片
        if (!originalFilename.matches(".*\\.(png|jpg|jpeg)$")) {
            return R.fail("请上传png或jpg格式图片");
        }

        System.out.println("=========开始识别身份证2========");

        Map<String, Object> params = new java.util.HashMap<>();
        OcrUtil ocrUtil = new OcrUtil(ocrProperties);
        params.put("image_name", originalFilename);
        try {
            if (originalFilename.endsWith(".jpg") || originalFilename.endsWith(".jpeg")) {
                params.put("image_name", originalFilename.split("\\.")[0]+".png");
                if (file.getSize() > 1024 * 1024) {
                    params.put("image_data", Base64.encode(ocrUtil.convertJpgToCompressedJpg(file,0.5f)));
                } else {
                    params.put("image_data", Base64.encode(ocrUtil.convertJpgToPngBytes(file)));
                }
            } else {
                if (file.getSize() > 1024 * 1024) {
                    params.put("image_data", Base64.encode(ocrUtil.compressPng(file)));
                } else {
                    params.put("image_data", Base64.encode(file.getBytes()));
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println("=========参数制作完成========"+params);
        OcrResult ocrResult = ocrUtil.sfzOcr(null, params);
        log.info("身份证识别结果：{}", ocrResult);
        if (ocrResult.getResult_code().equals("200")) {
            JSONObject jsonObject = JSONObject.parseObject(ocrResult.getResult_data());
            IDCardVo idCardVo = new IDCardVo();
            if (jsonObject.get("姓名") != "") {
                IDCardFront card = new IDCardFront();
                card.setCardName(jsonObject.get("姓名").toString());
                card.setSex(jsonObject.get("性别").toString());
                card.setResidentialAddress(jsonObject.get("住址").toString());
                card.setNationality(jsonObject.get("民族").toString());
                card.setCardNo(jsonObject.get("公民身份号码").toString());
                card.setAge(IDCardUtil.getAge(card.getCardNo()));
                idCardVo.setFront(card);
            } else {
                IDCardBack card = new IDCardBack();
                String validDate = jsonObject.get("有效期限").toString();
                card.setCardValidStartDate(validDate.split("-")[0]);
                card.setCardValidEndDate(validDate.split("-")[1]);
                card.setIssuingAuthority(jsonObject.get("签发机关").toString());
                idCardVo.setBack(card);
            }
            return R.ok("识别成功", idCardVo);
        } else {
            return R.fail("识别失败", ocrResult);
        }
    }

    @PostMapping("/sendSms")
    public R sendSms() {
        JXSmsTemplate jxSmsTemplate = new JXSmsTemplate(jxSmsProperties);
        String content = StrUtil.format(jxSmsProperties.getTemplate().get(1),
            MapBuilder.<String, Object>create()
                .put("code", "123457")
                .put("minute", "5")
                .build());
        JXSmsResult jxSmsResult = jxSmsTemplate.sendMsg("17371248795", content);
        return R.ok(jxSmsResult);
    }

    @PostMapping("/face/account_register.api")
    public R faceVerifyPerson(String openid, String accountType) {
        if (!faceProperties.getEnabled()) {
            return R.fail("请先开启人脸识别功能");
        }

        String url = faceProperties.getEndpoint() + faceProperties.getPrefix() + "/account_register.api?openId=" +
            openid + "&accountType=" + accountType;

        String post = HttpUtil.post(url, "");
        R ajax = JSONObject.parseObject(post, R.class);

        if (ajax.getCode() == 0) {
            ajax.setCode(500);
            ajax.setMsg("获取人脸认证失败");
            return ajax;
        }
        ajax.setCode(200);
        return ajax;
    }

    @PostMapping("/face/get_person_verify_url.api")
    public R getFaceVerifiedUrl(@RequestParam Map<String, String> params) {
        String url = faceProperties.getEndpoint() + faceProperties.getPrefix() + "/get_person_verify_url.api?customerId=" +
            params.get("customerId") +
            "&verifiedWay=" +
            params.get("verifiedWay") +
            "&pageModify=" +
            params.get("pageModify") +
            "&cert_type=" +
            params.get("cert_type") +
            "&customerIdentType=" +
            params.get("customerIdentType") +
            "&customerName=" +
            params.get("customerName") +
            "&customerIdentNo=" +
            params.get("customerIdentNo") +
            "&id_photo_optional=" +
            params.get("id_photo_optional") +
            "&result_type=" +
            params.get("result_type") +
            "&cert_flag=" +
            params.get("cert_flag") +
            "&is_mini_program=" +
            params.get("is_mini_program") +
            "&notifyUrl=" +
            params.get("notifyUrl") +
            "&returnUrl=" + params.get("returnUrl");
        String post = HttpUtil.post(url, "");
        R ajax = JSONObject.parseObject(post, R.class);

        if (ajax.getCode() == 0) {
            ajax.setCode(500);
            ajax.setMsg("获取人脸认证URL失败");
            return ajax;
        }
        ajax.setCode(200);
        return ajax;
    }

    @PostMapping("/face/notifyUrl")
    public void notifyUrl(@RequestParam Map<String, String> params) {
        System.out.println(params);
    }

    @PostMapping("/face/returnUrl")
    public void returnUrl(@RequestParam Map<String, String> params) {
        System.out.println(params);
    }

}
